<?php

namespace App\Http\Services;

use App\Http\Repositories\Daos\Order\OrderDao;
use App\Http\Repositories\Daos\Trade\TradeDao;
use App\Http\Requests\UserContext;
use App\Http\Traits\Errors;
use App\Util\Helper;
use App\Util\WechatPay\WechatPayUtil;

class TradeService extends BaseService
{
    use Errors;
    protected $tradeDao;
    protected $orderDao;

    public function __construct(TradeDao $tradeDao, OrderDao $orderDao)
    {
        $this->tradeDao = $tradeDao;
        $this->orderDao = $orderDao;
    }

    public function toPay(UserContext $userContext)
    {
        $tradeSn   = Helper::sn(20, 3);
        $orderSn   = request('order_sn') ?? '';
        $orderInfo = $this->goodsOrderInfo($orderSn);
        if(empty($orderInfo))$this->showError('订单不存在');
        $tradeData = [
            'trade_sn'   => $tradeSn,
            'user_id'    => $userContext->getId(),
            'pay_type'   => 'wechat_mini',
            'trade_type' => 'shop_order',
            'sub_type'   => 1,
            'order_sn'   => $orderSn,
            'order_ids'  => $orderInfo['id'],
            'amount'     => $orderInfo['pay_total'],
            'amount_pay' => $orderInfo['pay_total'],
            'platform'   => 'wx_mini',
        ];
        $this->tradeDao->save($tradeData);
        $payParam = [
            'order_sn'    => $orderSn,
            'description' => '甄选团购',
            'total_price' => $orderInfo['pay_total'],
            'openid'      => $userContext->getOpenId()
        ];
        return (new WechatPayUtil())->miniWechatPay($payParam);

    }

    //获取订单信息，方便日后处理订单金额传给交易数据
    public function goodsOrderInfo($orderSn)
    {
        $orderInfo              = $this->orderDao->getOne(['order_sn' => $orderSn]);
        $orderInfo['pay_total'] = Helper::yuanToCent($orderInfo['pay_total']);
        return $orderInfo;
    }
}
